<template>
    <section v-loading="loading">
        <!-- <section>
            <label class="num">梯内终端数：{{ terminalNum }}</label>
        </section> -->
        <el-form ref="ruleFormRef" label-position="top" :inline="true" require-asterisk-position="right"
            class="costEntryFormRef" :model="form" :rules="rules">
            <template v-for="(item, index) in form.list" :key="index">
                <section class="costEntrytitle">
                    <h3>明细{{ index + 1 }}</h3>
                    <span v-if="index !== 0 || item.id || (form.list.length > 1 && index === 0)" class="handelBtn"
                        @click="handelRemoveEntryForm(item, index)">删除</span>
                </section>
                <el-form-item label="终端类型" :prop="`list[${index}].terminalType`" :rules="rules.terminalType">
                    <el-select v-model="item.terminalType" filterable placeholder="请选择" multiple :disabled="item.id">
                        <el-option v-for="point in commonList.pointTypeList" :key="+point.code" :label="point.name"
                            :value="+point.code" />
                    </el-select>
                </el-form-item>
                <el-form-item label="合作模式" :prop="`list[${index}].cooperationModel`" :rules="rules.cooperationModel">
                    <el-select v-model="item.cooperationModel" filterable placeholder="请选择"
                        @change="item.contractPrice = ''">
                        <el-option v-for="model in modelList" :key="model.value" :label="model.label"
                            :value="model.value" />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="item.cooperationModel === 2" label="保底金金额" :prop="`list[${index}].guaranteedAmount`"
                    :rules="rules.guaranteedAmount">
                    <el-input v-model="item.guaranteedAmount" type="number">
                        <template #append> 元 </template>
                    </el-input>
                </el-form-item>
                <el-form-item v-if="item.cooperationModel === 2" label="甲方分成比例" :prop="`list[${index}].ownerShareRatio`"
                    :rules="rules.ownerShareRatio">
                    <el-input v-model="item.ownerShareRatio" type="number">
                        <template #append> % </template>
                    </el-input>
                </el-form-item>
                <el-form-item v-if="item.cooperationModel === 2" label="最低刊播价" :prop="`list[${index}].contractPrice`"
                    :rules="rules.contractPrice">
                    <el-input v-model="item.contractPrice" type="number">
                        <template #append> (元/台/天/条) </template>
                    </el-input>
                </el-form-item>
                <el-form-item v-if="item.cooperationModel === 1" :prop="`list[${index}].contractPrice`"
                    :rules="rules.contractPriceZu">
                    <template #label>
                        单价(年/台)
                        <el-tooltip placement="top">
                            <template #content>
                                【单价/年/台（元）= 合同金额/年/签约点位<br />数，年=合同开始到结束的间隔天数/365天 】
                            </template>
                            <i class="el-icon-question"></i>
                        </el-tooltip>
                    </template>
                    <template #default>
                        <el-input v-model="item.contractPrice" type="number">
                            <template #append> 元
                            </template>
                        </el-input>
                    </template>
                </el-form-item>
                <el-form-item label="合作周期" :prop="`list[${index}].time`" :rules="rules.time">
                    <el-date-picker v-model="item.time" type="daterange" range-separator="至" start-placeholder="开始时间"
                        end-placeholder="结束时间" value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item v-if="item.isShow" label="签约主体(对方)" :prop="`list[${index}].customerName`">
                    <el-input v-model="item.customerName" maxlength="200">
                    </el-input>
                </el-form-item>
                <el-form-item v-if="item.isShow" label="付款方式" :prop="`list[${index}].paymentType`">
                    <el-select v-model="item.paymentType" filterable placeholder="请选择">
                        <el-option label="月度" :value="1" />
                        <el-option label="季度" :value="2" />
                        <el-option label="半年" :value="3" />
                        <el-option label="年" :value="4" />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="item.isShow" label="税率" :prop="`list[${index}].saleTaxesRatio`">
                    <el-select v-model="item.saleTaxesRatio" filterable placeholder="请选择">
                        <el-option label="20%" :value="1" />
                        <el-option label="25%" :value="2" />
                        <el-option label="30%" :value="3" />
                    </el-select>
                </el-form-item>
                <el-form-item v-if="item.isShow" label="签约终端数" :prop="`list[${index}].signNum`" :rules="rules.signNum">
                    <el-input v-model="item.signNum" :maxlength="9" v-limitNumberBlur="{ min: 0, max: 999999999 }">
                    </el-input>
                </el-form-item>
                <el-form-item v-if="item.isShow" label="合作状态" :prop="`list[${index}].status`">
                    <el-select v-model="item.status">
                        <el-option label=" " :value="0" />
                        <el-option label="合作" :value="1" />
                        <el-option label="拆除" :value="2" />
                    </el-select>
                </el-form-item>
                <row v-if="item.isShow" style="width: 100%;">
                    <el-form-item label="附件" style="width: 100%;">
                        <xc-upload :limit="10" accept=".jpg,.pdf,.png"
                            :http-request="(file: File) => uploadFile(index, file)" :show-file-list="false"
                            tip="支持扩展名：jpg、png、pdf (最多上传9个)"></xc-upload>
                        <div v-for="(item, fileIndex) in item.premisesContractFileDTOS" :key="fileIndex" class="imgUpload">
                            <div class="imgInfo">
                                <el-icon size="14">
                                    <Document />
                                </el-icon>
                                <span class="img-name">{{
                                    item.fileName.length > 15 ? `${item.fileName.slice(0, 15)}...` : item.fileName
                                }}</span>
                            </div>
                            <div v-if="props.isEdit" class="handlCancel">
                                <!-- <span>({{ (item.size / 1024 / 1024).toFixed(2) }}M)</span> -->
                                <el-icon @click="handleRemove(index, fileIndex)">
                                    <DeleteFilled />
                                </el-icon>
                            </div>
                        </div>
                    </el-form-item>
                </row>
                <div v-if="props.showMore" class="more" @click="item.isShow = !item.isShow">
                    {{ item.isShow ? '收起更多' : '查看更多' }}
                    <el-icon color="#8C8C8C" class="moreIconClass">
                        <ArrowDown />
                    </el-icon>
                </div>
            </template>
        </el-form>
        <span class="handelBtn" style="margin-top: 20px;" @click="addEntryForm">+ 新增下一条</span>
        <TipsDailog title="提示" content="确定删除" :dialog-visible="dialogTipVisible" @onClose="dialogTipVisible = false">
            <el-button @click="dialogTipVisible = false"> 取消 </el-button>
            <el-button type="primary" @click="onConfirmDelete"> 确认
            </el-button>
        </TipsDailog>
    </section>
</template>

<script lang="ts" setup>
import { reactive, ref, computed, onMounted, watch, nextTick, defineEmits, defineProps, defineExpose } from 'vue';
import xcUpload from '@x-tech/fe-pc-components/src/components/XcUpload/index.vue';
import TipsDailog from '@/components/TipsDailog.vue';
import { useStore } from 'vuex';
import { Upload } from '@x-tech/fe-puma-lib-upload';
import type { FormInstance, FormRules } from 'element-plus';
import { getPremisesContract, deletePremisesContract } from '@/api/houseManage';
import { ElMessage } from 'element-plus';

const store = useStore();
const commonList: any = computed(() => store.state.app.common.CommonList);
const props = defineProps({
    applyOrderId: {
        type: String,
        default: '',
    },
    premiseId: {
        type: String,
        default: '',
    },
    isEdit: {
        type: Boolean,
        default: false,
    },
    showMore: {
        type: Boolean,
        default: false,
    },
});
const upl = new Upload(window.XCConfig.VITE_ENV);
const loading = ref(false);
const ruleFormRef = ref<FormInstance>();

const rules = {
    terminalType: [{ required: true, message: '请选择终端类型', trigger: 'change' }],
    cooperationModel: [{ required: true, message: '请选择合作模式', trigger: 'change' }],
    contractPriceZu: [{ required: true, message: '请输入单价', trigger: 'change' }],
    contractPrice: [
        { required: true, message: '请输入0-0.47之间的数字', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                try {
                    // 校验格式
                    let reg = /^([0]|([1-9][0-9]*)|(([0]\.\d{1,}|[1-9][0-9]*\.\d{1,})))$/;
                    if (!reg.test(value)) {
                        callback(new Error('输入格式不正确'));
                        return;
                    }

                    reg = /^([0]|([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                    if (!reg.test(value)) {
                        callback(new Error('最多保留两位小数'));
                        return;
                    }
                    const fValue = parseFloat(value);
                    if (fValue < 0 || fValue > 0.47) {
                        // eslint-disable-next-line no-useless-escape
                        callback(new Error('请输入0-0.47之间的数字'));
                    } else {
                        callback();
                    }
                } catch (error) {
                    callback(new Error('请输入0-0.47之间的数字'));
                }
            },
            trigger: 'blur',
        },
    ],
    time: [{ required: true, message: '请选择合作周期', trigger: 'change' }],
    ownerShareRatio: [
        { required: true, message: '请输入0-100的数字', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                try {
                    // 校验格式
                    let reg = /^([0]|([1-9][0-9]*)|(([0]\.\d{1,}|[1-9][0-9]*\.\d{1,})))$/;
                    if (!reg.test(value)) {
                        callback(new Error('输入格式不正确'));
                        return;
                    }
                    reg = /^([0]|([1-9][0-9]*)|(([0]\.\d{1,2}|[1-9][0-9]*\.\d{1,2})))$/;
                    if (!reg.test(value)) {
                        callback(new Error('最多保留两位小数'));
                        return;
                    }
                    // 校验大小
                    const fValue = parseFloat(value);

                    if (fValue > 100 || fValue < 0) {
                        // eslint-disable-next-line no-useless-escape
                        callback(new Error('请输入0-100的数字'));
                    } else {
                        callback();
                    }
                } catch (error) {
                    callback(new Error('请输入0-100的数字'));
                }
            },
            trigger: 'blur',
        },
    ],
    guaranteedAmount: [
        { required: true, message: '请输入≥0的数字', trigger: 'blur' },
        {
            validator: (rule, value, callback) => {
                try {
                    const reg = /^([0]|([1-9][0-9]*)|(([0]\.\d{1,}|[1-9][0-9]*\.\d{1,})))$/;
                    if (!reg.test(value)) {
                        callback(new Error('输入格式不正确'));
                        return;
                    }
                    const intValue = parseInt(value);
                    if (intValue < 0) {
                        // eslint-disable-next-line no-useless-escape
                        callback(new Error('请输入≥0的数字'));
                    } else {
                        callback();
                    }
                } catch (error) {
                    callback(new Error('请输入≥0的数字'));
                }
            },
            trigger: 'blur',
        },

    ],
    signNum: [
        { required: true, message: '请输入签约终端数', trigger: 'blur' }
        // {
        //     validator: (rule, value, callback) => {
        //         try {
        //             const reg = /^[1-9]\d*|0$/;
        //             if (!reg.test(value)) {
        //                 callback(new Error('请输入>=0的整数'));
        //             }
        //             return true;
        //         } catch (error) {
        //             callback(new Error('请输入≥0的数字'));
        //         }
        //     },
        //     trigger: 'blur',
        // }
    ]


};
const modelList = ref([
    { value: 1, label: '租用模式' },
    { value: 2, label: '分成模式' },
]);
const form = reactive({
    list: [
        {
            applyOrderId: props.applyOrderId, //	integer($int64)屏盟楼盘申请ID
            contractPrice: '', //	number最低刊价播/单价
            cooperationModel: 1, //	integer($int32)合作模式 (1：租用；2：分成)
            createUserName: '', //	string创建人
            customerName: '', //	string 签约主体
            endDate: '', //	string($date-time)合作周期结束日期
            guaranteedAmount: '', //	number保底金额
            ownerShareRatio: '', //	number甲方分成比例
            paymentType: '', //	string付款方式
            premiseId: props.premiseId, //	integer($int64)楼盘ID
            premisesContractFileDTOS: [], //	[...]
            saleTaxesRatio: '', //	number销售税费比例
            signNum: '',     // 签约终端数量
            status: 1,//合作状态
            startDate: '', //	string($date-time)合作周期开始日期
            terminalType: [], //	integer($int32)终端类型(1：梯内屏；2：梯外屏；3：梯内框；4：梯外框
            updateUserName: '', // string修改人
            time: '',
            isShow: !props.showMore,
            id: undefined
        },
    ],
});
const isCostEntry = ref(true);
const dialogTipVisible = ref(false);
const currentId = ref('');
const currentIndex = ref(0);
console.log(props.applyOrderId);
const getPremisesContractList = async () => {
    loading.value = true;

    const data = await getPremisesContract({ applyOrderId: props.applyOrderId });

    console.log('data----', data);
    if (data.length) {
        form.list = data.map((item: any) => {
            return {
                ...item,
                time: [item.startDate, item.endDate],
                terminalType: item.terminalTypeList.map((terminal: any) => terminal.terminalType),
                terminalTypeListCopy: item.terminalTypeList,
                isShow: true,
            };
        });
    }
    const isEdit = !data.length;
    store.commit('plan/setIsEdit', isEdit);
    loading.value = false;
};
onMounted(async () => {
    if (props.applyOrderId) {
        getPremisesContractList();
    }
});

const uploadFile = async (index: number, file: File) => {
    let _file: any = file;
    if (Array.isArray(file) && file.length) {
        _file = file[0];
    }
    const res = await upl.uploadWithoutFilename(_file.file!, false);
    const item: object = { fileUrl: res, fileName: _file.file.name, size: _file.file.size, contractId: '', id: '' };
    form.list[index].premisesContractFileDTOS.push(item);
};
const handleRemove = (index: number, i: number) => {
    form.list[index].premisesContractFileDTOS.splice(i, 1);
};
const addEntryForm = () => {
    const item = {
        applyOrderId: props.applyOrderId, //	integer($int64)屏盟楼盘申请ID
        contractPrice: '', //	number最低刊价播/单价
        cooperationModel: 1, //	integer($int32)合作模式 (1：租用；2：分成)
        createUserName: '', //	string创建人
        customerName: '', //	string 签约主体
        endDate: '', //	string($date-time)合作周期结束日期
        guaranteedAmount: '', //	number保底金额
        ownerShareRatio: '', //	number甲方分成比例
        paymentType: '', //	string付款方式
        premiseId: props.premiseId, //	integer($int64)楼盘ID
        premisesContractFileDTOS: [], //	[...]
        saleTaxesRatio: '', //	number销售税费比例
        signNum: '',  //
        status: 1,
        startDate: '', //	string($date-time)合作周期开始日期
        terminalType: [], //	integer($int32)终端类型(1：梯内屏；2：梯外屏；3：梯内框；4：梯外框
        updateUserName: '', // string修改人
        time: '',
        isShow: !props.showMore,
    };
    form.list.unshift(item);
};

const handelRemoveEntryForm = async (item: any, index: number) => {
    // if (!item.id) {
    //     form.list.splice(index, 1);
    // } else {
    // }
    currentIndex.value = index;
    currentId.value = item.id;
    dialogTipVisible.value = true;
};
const onConfirmDelete = async () => {
    if (currentId.value) {
        await deletePremisesContract({ id: currentId.value });
        form.list.splice(currentIndex.value, 1);
        // getPremisesContractList();
    } else {
        form.list.splice(currentIndex.value, 1);
    }

    ElMessage.success('删除成功');
    dialogTipVisible.value = false;
};
const submitForm = () => {
    if (!ruleFormRef.value) {
        return;
    }

    return new Promise((resove, reject) => {
        ruleFormRef.value.validate((isvalid: boolean) => {
            if (!isvalid) {
                reject(new Error('请完善信息'));
            }
            else {
                const formList = form.list.map((item: any) => {
                    return {
                        ...item,
                        startDate: item.time[0],
                        endDate: item.time[1],
                        terminalTypeList: item.terminalType.map((terminal: any) => {
                            const objTerminal = item.terminalTypeListCopy
                                ? item.terminalTypeListCopy.find(
                                    (oldTerminal: any) => +oldTerminal.terminalType === +terminal
                                )
                                : false;
                            if (objTerminal) {
                                return objTerminal;
                            }
                            return { terminalType: terminal, contractId: '', id: '' };
                        }),
                    };
                });
                resove(formList);
            }
        });
    })
};

// 对外暴露可执行方法
defineExpose({
    submitForm,
});
</script>

<style lang="scss" scoped>
.costEntrytitle {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin: 20px 0;

    h3 {
        font-size: 16px;
        color: #333;
    }

    label {
        font-size: 16px;
        color: #999;
    }
}

.num {
    font-size: 16px;
    color: #999999;
}

.handelBtn {
    display: inline-block;
    width: 100px;
    text-align: right;
    font-size: 16px;
    color: #e60044;
    cursor: pointer;
}

.costEntryFormRef {
    display: flex;
    justify-content: space-between;

    :deep(.el-form-item.is-required > .el-form-item__label::after) {
        content: '*';
        color: var(--el-color-danger);
        margin-left: 3px;
    }

    :deep(.el-form-item__content) {
        width: 280px;
    }

    :deep(.el-form-item) {
        margin-right: 0;
    }

    :deep(.el-upload__tip) {
        margin-bottom: 0 !important;
    }

    .more {
        width: 100%;
        text-align: center;
        font-size: 14px;
        padding-bottom: 20px;
        border-bottom: 1px solid #ddd;
        cursor: pointer;

        .moreIconClass {
            vertical-align: middle;
        }
    }
}

.imgUpload {
    position: relative;
    width: 360px;
    height: 32px;
    padding: 0 15px;
    background: #ffffff;
    border-radius: 4px 4px 4px 4px;
    opacity: 1;
    border: 1px solid #d9d9d9;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin: 0 15px 10px 0;

    .imgInfo {
        display: flex;
        align-items: center;

        .img-name {
            padding: 0 10px;
            word-break: break-all;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
            font-size: 12px;
            color: #252525;
        }
    }

    .handlCancel {
        span {
            font-size: 12px;
            color: #999999;
            padding-right: 10px;
        }

        .el-icon {
            cursor: pointer;
            vertical-align: middle;
        }
    }
}
</style>
